package com.daocao.common.utils;


import cn.hutool.core.util.StrUtil;
import com.daocao.common.constants.CacheConstants;
import com.daocao.common.entity.vo.LoginUserVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class JwtUtils {

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    private String secret = "sdasdasd";

    /**
     * 创建 Token
     *
     * @param loginUserVo
     * @return token
     */
    public String createToken(LoginUserVo loginUserVo) {
        String token = UUID.randomUUID().toString().replace("-", "");
        loginUserVo.setToken(token);
        loginUserVo.setLoginTime(System.currentTimeMillis());
        Map<String, Object> claims = new HashMap<>();
        claims.put("token", token);
        refreshToken(loginUserVo);
        return Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 解析 Token
     *
     * @return Claims
     */
    public Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 获取登录用户, 根据 token 进行解析
     *
     * @return Object
     */
    public Object getLoginUser(HttpServletRequest request) {
        String token = request.getHeader("Daocao-Authorization");
        if (StrUtil.isNotEmpty(token)) {
            Claims claims = parseToken(token);
            String parsseToken = (String) claims.get("token");
            LoginUserVo loginUserVO = redisCacheUtil.getCacheObject(CacheConstants.LOGIN_USER_KEY + parsseToken);
            long loginTime = loginUserVO.getLoginTime();
            long currentTimeMillis = System.currentTimeMillis();
            long millis = currentTimeMillis / 1000 / 60 - loginTime / 1000 / 60;
            if (millis >= 20) {
                refreshToken(loginUserVO);
            }
            return loginUserVO;
        }
        return null;
    }

    /**
     * 刷新 Token
     */
    private void refreshToken(LoginUserVo loginUserVo) {
        redisCacheUtil.setCacheObject(CacheConstants.LOGIN_USER_KEY + loginUserVo.getToken(), loginUserVo, 30, TimeUnit.MINUTES);
    }
}
